﻿using System;
using System.Collections.Generic;
using UnityEngine;

namespace CGF
{
    public class MainThread : MonoBehaviour
    {
        private static MainThread instance;
        private static Queue<Action> actionQueue = new Queue<Action>();

        public static void Run(Action action)
        {
            if (!instance)
            {
                Debug.LogError("请在最早时间将 MainThread 脚本绑定到场景中任意对象上");
                return;
            }
            actionQueue.Enqueue(action);
        }

        private void Awake()
        {
            instance = this;
        }

        public void Update()
        {
            if (actionQueue.Count > 0)
            {
                lock (actionQueue)
                {
                    while (actionQueue.Count > 0)
                    {
                        Action action = actionQueue.Dequeue();
                        action?.Invoke();
                    }
                }
            }
        }

    }
}